﻿using System;
using System.Collections.Generic;
using EasyLib.Utils;

namespace EasyLib.Cache
{
    public class SimpleCache
    {
        #region 属性及初始化
        /// <summary>
        /// simulate cache with dictionary
        /// </summary>
        public static IDictionary<string, object> Cache { get; set; }

        private static readonly object lockobj = new object();

        static SimpleCache()
        {
            lock (lockobj)
            {
                if (Cache == null)
                {
                    Cache = new Dictionary<string, object>();
                }
            }
        }

        public int Count
        {
            get { return Cache.Count; }
        }

        #endregion

        #region 缓存方法
        public static void Insert<TData>(string key, Func<TData> dataGetter)
        {
            Cache[key] = dataGetter();
        }

        public static void Insert(string key, object value)
        {
            Cache[key] = value;
        }

        public static bool IsInCache(string key)
        {
            return Cache.ContainsKey(key);
        }

        public static void Remove(string key)
        {
            if (!Cache.ContainsKey(key))
            {
                return;
            }
            Cache.Remove(key);
        }

        public static T Get<T>(string key)
        {
            if (Cache.ContainsKey(key))
            {
                return TypeConvertUtils.ConvertType<T>(Cache[key]);
            }
            return default(T);
        }

        public static T Get<T>(string key, Func<T> dataGetter)
        {
            if (Cache.ContainsKey(key)) return Get<T>(key);
            T data = dataGetter();
            Insert(key, data);
            return data;
        }
        #endregion
    }
}
